package client.comm.commlib.widget

import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager

class LoadMoreRecyclerView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : RecyclerView(context, attrs, defStyleAttr) {
    private var mTouchSlop = 0
    private var mYDown = 0f
    private var mLastY = 0f

    init {
        mTouchSlop = ViewConfiguration.get(getContext()).scaledTouchSlop

        addOnScrollListener(object : OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                onLoadMore?.let {
                    if (canLoad()) {
                        it.invoke()
                    }
                }
            }
        })
    }


    override fun dispatchTouchEvent(event: MotionEvent): Boolean {
        val action = event.action
        when (action) {
            MotionEvent.ACTION_DOWN -> mYDown = event.rawY
            MotionEvent.ACTION_MOVE -> mLastY = event.rawY
        }
        return super.dispatchTouchEvent(event)
    }

    fun canLoad(): Boolean {
        return isScrollBottom() && isPullUp()
    }

    var onLoadMore: (() -> Unit)? = null

    //是否向上滑动
    private fun isPullUp(): Boolean {
        return mYDown - mLastY >= mTouchSlop
    }

    private fun isScrollBottom(): Boolean {
        adapter?.let {
            return (it.itemCount > 0 && getLastVisiblePosition() == it.itemCount - 1)
        }
        return false
    }

    fun getLastVisiblePosition(): Int {

        layoutManager?.let {
            val position: Int
            if (it is LinearLayoutManager) {
                position =
                    (it).findLastVisibleItemPosition()
            } else if (it is GridLayoutManager) {
                position =
                    (it).findLastVisibleItemPosition()
            } else if (it is StaggeredGridLayoutManager) {
                val lastPositions: IntArray =
                    it.findLastVisibleItemPositions(IntArray(it.getSpanCount()))
                position = getMaxPosition(lastPositions)
            } else {
                position = it.getItemCount() - 1
            }

            return position
        }

        return -1
    }

    private fun getMaxPosition(positions: IntArray): Int {
        var maxPosition = Int.MIN_VALUE
        for (position in positions) {
            maxPosition = Math.max(maxPosition, position)
        }
        return maxPosition
    }
}